package example;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.io.File;
import java.io.RandomAccessFile;

/**
 * 支绍昆 2018/10/12 0012
 */
public class FileUploadServerHandler extends ChannelInboundHandlerAdapter {

    private int byteRead;
    private volatile int start = 0;
    private String file_dir = "H:";

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws  Exception {
        super.channelActive(ctx);
        System.out.println("service : channel active;");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        System.out.println("service : channel inactive;");
        ctx.flush();
        ctx.close();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception{
        if (msg instanceof FileUpload){
            FileUpload fu = (FileUpload) msg;
            byte[] bytes = fu.getBytes();
            byteRead = fu.getEndPos();

            String name = fu.getName();
            String path = file_dir + File.separator + name;
            File file = new File(path);

            RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
            randomAccessFile.seek(start);
            randomAccessFile.write(bytes);
            start = start + byteRead;
            System.out.println("path:" + path + "," + byteRead);

            if (byteRead > 0){
                ctx.writeAndFlush(start);
                randomAccessFile.close();
                if (byteRead != 1024 * 10){
                    channelInactive(ctx);
                }
            }else {
                System.out.println("file finish .");
                ctx.close();
            }
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }

}
